package com.sinopac.action.main;

import java.util.HashMap;
import java.util.Map;

import netfusion.jbranch.encrypt.md5.MD5Util;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.sinopac.actionCore.ActionCore;
import com.sinopac.model.main.MainModel;


@Namespace("/Index")
public class MainAction extends ActionCore{
	
	private static final long serialVersionUID = 1L;
	private Boolean errorFlag = false;
	private Boolean pdfFlag = false;
	private String pdfPath;
	private String custId;
	private Integer function_num;
	private String token_esn;
	private String from_h;
	private String to_h;
	private String token_cust;
	private String record;
	private String from_i;
	private String to_i;
	private String sort;
	private String errorMessage;
	private String token_id;
	
	private String errorMessageForSyn;
	
	private static final String FUNCTION1 = "function1";
	private static final String FUNCTION2 = "function2";
	private static final String FUNCTION3 = "function3";
	private static final String FUNCTION4 = "function4";
	private static final String FUNCTION5 = "function5";
	private static final String FUNCTION6 = "function6";
	private static final String FUNCTION7 = "function7";
	private static final String FUNCTION8 = "function8";
	private static final String FUNCTION9 = "function9";
	private static final String FUNCTION10 = "function10";
	private static final String FUNCTION11 = "function11";
	
	//使用者登入帳號
	private String userName;
	//使用者角色
	private String userRoles;
	//測試
	private Map<String,String> userList = new HashMap<String, String>();
	
	@Action(value="test",results={@Result(name="input",location="/form/Test/loginTest.jsp")})
	public String test(){
		MainModel mm = new MainModel();
		userList = mm.getTestList();
		return INPUT;
	}
	
	@Action(value="login",results={@Result(name="login",location="/form/Index/mainLogout.jsp")})
	public String execute(){
		if(session.size()>0){
			userName = session.get("userName").toString();
		}
		return LOGIN;
	}
	
	@Action(value="index",results={@Result(name="login",location="/form/Index/main.jsp"),
								   @Result(name="input",location="/form/Index/mainLoginErr.jsp")})
	public String index(){		
		userName = ServletActionContext.getRequest().getParameter("UserID");
		String md5 = ServletActionContext.getRequest().getParameter("MD5");
		String clientIP = ServletActionContext.getRequest().getRemoteAddr();
		System.out.println("ClientIP:"+clientIP);
//		String otpMd5 = PropsUtil.getConfig("otpmd5");
//		StringBuffer md5_str = new StringBuffer();
//		md5_str.append(userName);
//		md5_str.append("OTP");
//		String newMd5 = MD5Util.calc(md5_str.toString());
//		System.out.println("md5_str:"+md5_str.toString());
//		System.out.println("MD5:"+md5);
//		System.out.println("newMd5:"+newMd5);
		
		if(session.size()>0){
			userName = (String)session.get("userName");
			md5 = (String)session.get("newMd5");
			if(StringUtils.isNotBlank((String)session.get("pdfPath"))){
				pdfFlag = true;
				pdfPath = (String)session.get("pdfPath");
				System.out.println("session.get('pdfPath'):"+pdfPath);
			}
		}
		
		MainModel mm = new MainModel();
			if(StringUtils.isNotBlank(userName)){
				StringBuffer md5_str = new StringBuffer();
				md5_str.append(userName);
				md5_str.append("OTP");
				String newMd5 = MD5Util.calc(md5_str.toString());
				System.out.println("md5_str:"+md5_str.toString());
				System.out.println("MD5:"+md5);
				System.out.println("newMd5:"+newMd5);
				
				userRoles = mm.getRoles(userName);
				if(StringUtils.isBlank((String)session.get(USER_NAME))){
					if(userRoles.equals("")){  // userRoles.equals("9") || 
	//				System.out.println("Result: 10");
						// 10 使用者不存在
						session.clear();
						mm.insertLoginLog("","",clientIP,"10");
						return INPUT;
					}else if(!md5.toLowerCase().equals(newMd5)){
	//				System.out.println("Result: 14");
						// 14 MD5驗證碼錯誤(登入分行平台時驗證)
						mm.insertLoginLog(userName,userRoles,clientIP,"14");
						return INPUT;
					}else if(StringUtils.isNotBlank(userRoles) && md5.toLowerCase().equals(newMd5)){
						// 01 成功
	//				System.out.println("Result: 01");
						session.put("userName", userName);
						session.put("newMd5", newMd5);
						session.put("userRoles", userRoles);
						mm.insertLoginLog(userName,userRoles,clientIP,"01");
					}
				}
			}else{
				// 10 使用者不存在
//			System.out.println("Result: 10 & 10");
				mm.insertLoginLog("","",clientIP,"10");
				return INPUT;
			}
		
//		if(StringUtils.isNotBlank(userName) && md5.toLowerCase().equals(newMd5)){
//			session.put("userName", userName);
//			session.put("newMd5", newMd5);
//			userRoles = mm.getRoles(userName);
//			System.out.println("userRoles:"+userRoles);
//			session.put("userRoles", userRoles);
//			if(userRoles.equals("")){  // userRoles.equals("9") || 
//				session.clear();
//				return INPUT;
//			}
//		}else{
//			return INPUT;
//		}
//		System.out.println("errorMessageB:" + errorMessage + errorFlag);
		return LOGIN;
	}
	
	@Action(value="chkCustId",results={@Result(name="success",type="chain",location="forwardAction"),
									   @Result(name="error",type = "chain" ,location="index")})
	public String chkCustId(){
		pdfFlag = false;
		pdfPath = "";
		session.put("pdfPath", "");
		errorFlag = true;
//		System.out.println("custId_a:"+custId);
		Boolean custFlag = false, tokenFlag = false;
		MainModel mm = new MainModel();
		StringBuffer custIdMix = new StringBuffer();
		if(StringUtils.isNotBlank(custId)){//判斷客戶ID
			// 客戶ID前面18位未滿的話補空白
			if(custId.length()<23){
				String[] strlist = custId.split("-");
				custIdMix.append(strlist[0].toString());
				for(int i=1; i<=18-strlist[0].length(); i++){
					custIdMix.append(" ");
				}
				custIdMix.append("-" + strlist[1].toString() + "-" + strlist[2].toString());
//				System.out.println("cusId1:"+custIdMix.toString());
				custFlag = mm.chkCustID(custIdMix.toString());
				if(custFlag){
					session.put(CustomersID, custIdMix.toString());
					return SUCCESS;
				}
			}else{
				custFlag = mm.chkCustID(custId);
				if(custFlag){
					session.put(CustomersID, custId);
					return SUCCESS;
				}
			}
		}else if(StringUtils.isNotBlank(token_esn)){
			tokenFlag = mm.chkToken_esn(token_esn);
			if(tokenFlag){
				session.put(TOKEN_ESN, token_esn);
				return SUCCESS;
			}
		}else if (StringUtils.isNotBlank(record)) {
//			custFlag = true;
			StringBuffer sb = new StringBuffer();
			if(StringUtils.isNotBlank(token_cust)){
				String[] strtemp = token_cust.split("-");
				if(token_id.equals("2")){
					sb.append(StringUtils.rightPad(strtemp[0], 18, " ")+"-");
					sb.append(strtemp[1]+"-");
					sb.append(strtemp[2]);
					token_cust = sb.toString();
				}
			}
			session.put("from_h", from_h);
			session.put("to_h", to_h);
			session.put("token_cust", token_cust);
			session.put("record", record);	
			return SUCCESS;
		}else if (StringUtils.isNotBlank(sort)) {
			session.put("from_i", from_i);
			session.put("to_i", to_i);
			session.put("sort", sort);
			return SUCCESS;
		}
		errorMessage = StringUtils.isNotBlank(mm.getErrorMessage())?mm.getErrorMessage():"";
		if(StringUtils.isBlank(errorMessage)){
			errorFlag = false;
		}
//		System.out.println("errorMessageA:" + errorMessage + errorFlag);
		return ERROR;
	}
	
	@Action(value="forwardAction",results={@Result(name="function1",type="redirect",location="/GroupManagement/index"),
									   @Result(name="function2",type="redirect",location="/CustomerApply/index"),
									   @Result(name="function3",type="redirect",location="/BatchFile/index"),
									   @Result(name="function4",type="redirect",location="/TokenManagement/index"),
									   @Result(name="function5",type="redirect",location="/TokenSynchronous/index"),
									   @Result(name="function6",type="redirect",location="/TokenStorage/index"),
									   @Result(name="function7",type="redirect",location="/SupervisorReconfirm/index"),
									   @Result(name="function8",type="redirect",location="/LogQuery/index"),
									   @Result(name="function9",type="redirect",location="/RptQuery/index"),
									   @Result(name="function10",type="redirect",location="/CustomerApply/idQuery"),
									   @Result(name="function11",type="redirect",location="/ccroger/index"),
									   @Result(name="login",location="/form/Index/main.jsp")})
	public String forwardAction(){
		pdfFlag = false;
		pdfPath = "";
		session.put("pdfPath", "");
		switch(function_num){
			case 1:
				return FUNCTION1;
			case 2:
				return FUNCTION2;
			case 3:
				return FUNCTION3;
			case 4:
				return FUNCTION4;
			case 5:
				return FUNCTION5;
			case 6:
				return FUNCTION6;
			case 7:
				return FUNCTION7;
			case 8:
				return FUNCTION8;
			case 9:
				return FUNCTION9;
			case 10:
				return FUNCTION10;
			case 11:
				return FUNCTION11;
		}
		return LOGIN;
	}
	
	@Action(value = "chkTokenAndStatus", results = {
			@Result(name = "login", type = "chain" , location="index"),
			@Result(name = "success", type = "redirect", location = "/TokenSynchronous/execute") })
	public String chkTokenAndStatus() {
		pdfFlag = false;
		pdfPath = "";
		session.put("pdfPath", "");
		MainModel mm = new MainModel();
		Boolean tokenFlag = false; 
		if(StringUtils.isNotBlank(token_esn)){
			tokenFlag = mm.chkToken_Status(token_esn);
			if(tokenFlag){
				session.put(TOKEN_ESN, token_esn);
				return SUCCESS;
			}
		}
		if(StringUtils.isNotBlank(mm.getErrorMessageForSyn())){
			errorFlag=true;
			errorMessage = StringUtils.isNotBlank(mm.getErrorMessageForSyn())?mm.getErrorMessageForSyn():"";
		}
		return LOGIN;
	}
	
	public String getFrom_h() {
		return from_h;
	}

	public void setFrom_h(String from_h) {
		this.from_h = from_h;
	}

	public String getTo_h() {
		return to_h;
	}

	public void setTo_h(String to_h) {
		this.to_h = to_h;
	}
	
	public String getFrom_i() {
		return from_i;
	}

	public void setFrom_i(String from_i) {
		this.from_i = from_i;
	}

	public String getTo_i() {
		return to_i;
	}

	public void setTo_i(String to_i) {
		this.to_i = to_i;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getToken_cust() {
		return token_cust;
	}

	public void setToken_cust(String token_cust) {
		this.token_cust = token_cust;
	}

	public String getRecord() {
		return record;
	}

	public void setRecord(String record) {
		this.record = record;
	}

	public Boolean getErrorFlag() {
		return errorFlag;
	}

	public void setErrorFlag(Boolean errorFlag) {
		this.errorFlag = errorFlag;
	}

	public String getCustId() {
		return custId;
	}

	public void setCustId(String custId) {
		this.custId = custId;
	}

	public Integer getFunction_num() {
		return function_num;
	}

	public void setFunction_num(Integer function_num) {
		this.function_num = function_num;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(String userRoles) {
		this.userRoles = userRoles;
	}

	public String getToken_esn() {
		return token_esn;
	}

	public void setToken_esn(String token_esn) {
		this.token_esn = token_esn;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getErrorMessageForSyn() {
		return errorMessageForSyn;
	}

	public void setErrorMessageForSyn(String errorMessageForSyn) {
		this.errorMessageForSyn = errorMessageForSyn;
	}

	public Boolean getPdfFlag() {
		return pdfFlag;
	}

	public void setPdfFlag(Boolean pdfFlag) {
		this.pdfFlag = pdfFlag;
	}

	public String getPdfPath() {
		return pdfPath;
	}

	public void setPdfPath(String pdfPath) {
		this.pdfPath = pdfPath;
	}

	public String getToken_id() {
		return token_id;
	}

	public void setToken_id(String token_id) {
		this.token_id = token_id;
	}

	public Map<String, String> getUserList() {
		return userList;
	}

	public void setUserList(Map<String, String> userList) {
		this.userList = userList;
	}
		
}
